#include "tcpS.h"

void PC_Server(void)
{
	int socketID = 0;
	int newID = 0;
	int ret = 0;
	int addrLen = 0;
	int maxFd = 0;
	int i = 0;
	char buf[SIZE] = {0};
	struct sockaddr_in addr;
	fd_set readFds;
	fd_set tmpFds;
	
	//socket
	socketID = socket(AF_INET, SOCK_STREAM, 0);
	if (socketID < 0)
	{
		perror("socket error");
	//	return -1;
		return ;
	}
	//bind 
	addrLen = sizeof(addr);
	memset(&addr, 0, addrLen);
	addr.sin_family = AF_INET;
	addr.sin_port = htons(PORT);
	addr.sin_addr.s_addr = INADDR_ANY;
	if (0 > bind(socketID, (struct sockaddr *)&addr, addrLen))
	{
		perror("bind error");
		close(socketID);
	//	return -1;
		return ;
	}
	//listen
	listen(socketID, 5);
	printf("socket ok, bind ok , listen ok\r\n");
	
	maxFd = socketID;
	FD_ZERO(&readFds);
	FD_SET(socketID, &readFds);
	
	//select 
	while(1)
	{
		tmpFds = readFds;
		printf("before call select \r\n");
		ret = select(maxFd + 1, &tmpFds, NULL, NULL, NULL);
        printf("ret=%d\n",ret);
		if (ret < 0)
		{
			perror("select error");
			continue;
		}
		else if (0 == ret)
		{
			printf("select time out\r\n");
			break;
		}
		for (i = 0; i < maxFd + 1; i++)
		{
			if (FD_ISSET(i, &tmpFds))
			{
				if (socketID == i)
				{
					newID = accept(i, (struct sockaddr *)&addr, &addrLen);
					if (newID > 0)
					{
						FD_SET(newID, &readFds);
						if (maxFd < newID)
						{
							maxFd = newID;
						}
					}
				}
				else  //if (socketID != i && FD_ISSET(i, &tmpFds))
				{
					ret = recv(i, buf, SIZE - 1, 0);
                    perror("buf");
					if (ret < 0)
					{
						perror("recv error");
						close(i);
						FD_CLR(i, &readFds);
					}
					else if (0 == ret)
					{
						close(i);
						FD_CLR(i, &readFds);
					}
					else
					{
						printf("server get :%s\r\n", buf);
						send(i, buf, ret, 0);
 
 
					}
				}////if (socketID != i && FD_ISSET(i, &tmpFds))
			}//if (FD_ISSET(i, &tmpFds))
		}//for (i = 0; i < maxFd + 1; i++)		
	}//while(1)

	close(socketID);
	
}

